﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;

namespace FirmwareUpdater
{
    public partial class Updater : Form
    {
        public Updater()
        {
            InitializeComponent();
        }

        private void btnOpenFirmware_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.CheckFileExists = true;
            dlg.Filter = "Hex 文件(.hex)|*.hex";

            if (dlg.ShowDialog() == DialogResult.OK)
                tbxFirmware.Text = dlg.FileName;
        }

        private void Updater_Load(object sender, EventArgs e)
        {
            cbxBuadRate.SelectedIndex = 0;
            cbxCOM.Items.Clear();
            cbxCOM.Items.AddRange(SerialPort.GetPortNames());
            cbxCOM.SelectedIndex = 0;
        }

        private void cbxCOM_Click(object sender, EventArgs e)
        {
            cbxCOM.Items.Clear();
            cbxCOM.Items.AddRange(SerialPort.GetPortNames());
        }

        private void button2_Click(object sender, EventArgs e)
        {
            int buadRate = 0;

            if (!File.Exists(tbxFirmware.Text))
            {
                MessageBox.Show(this, "请选择固件", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                tbxFirmware.Focus();
                return;
            }
            else if (string.IsNullOrEmpty(cbxCOM.Text))
            {
                MessageBox.Show(this, "请选择串口", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cbxCOM.Focus();
                return;
            }
            /*else if (!int.TryParse(cbxBuadRate.Text, out buadRate))
            {
                MessageBox.Show("请选择波特率", "错误");
                cbxBuadRate.Focus();
                return;
            }*/

            progressBar1.Value = 0;
            IntelHex hexFile = new IntelHex();
            try
            {

                hexFile.Load(tbxFirmware.Text);
            }
            catch (Exception)
            {
                MessageBox.Show(this, "错误的Hex文件", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }


            ArduinoSTK sp;

            try
            {
                sp = new ArduinoSTK();
                sp.PortName = cbxCOM.Text;
                sp.BaudRate = 57600;
                sp.DtrEnable = true;
                sp.Open();
            }
            catch
            {
                MessageBox.Show(this, "开启串口错误", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            lbStatus.Text = "连接...";
            bool fail = false;

            Console.Write("Connectiong...");
               
            if (sp.connectAP())
            {
                Console.WriteLine("done");
                sp.Progress += (progress) =>
                    {
                        lbStatus.Text = "上传" + progress + "%";
                        progressBar1.Value = progress;
                    };

                try
                {
                    if (!sp.uploadflash(hexFile.RawData, 0, hexFile.RawData.Length, 0))
                    {
                        if (sp.IsOpen)
                            sp.Close();

                        MessageBox.Show(this, "上传失败，请用 Arduino 上传",
                            "错误",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Warning);
                    }
                }
                catch (Exception ex)
                {
                    fail = true;
                    MessageBox.Show(this, ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }
            else
            {
                Console.WriteLine("failed");
                fail = true;
                MessageBox.Show(this, "无法连接到目标板", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            sp.Close();

            if (fail)
            {
                lbStatus.Text = "失败";
            }
            else
            {
                lbStatus.Text = "成功";
                MessageBox.Show(this, "升级完成!", "", MessageBoxButtons.OK);
            }
        }
    }
}
